<?php
class helper_form_select extends system_view_helper_formElement {
	
	public function select($name, $value = null, $attribs = null, $options = null) {
		$info = $this->_getInfo($name, $value, $attribs, $options);
		
		$value = array_map('strval', (array) $value);
		
		$multiple = '';		
		if(substr($name, -2) == '[]') {
			$multiple = ' multiple="multiple"';
		}
		
		if(isset($attribs['multiple'])) {
			if($attribs['multiple']) {
				$multiple = ' multiple="multiple"';
				if(!empty($multiple) && (substr($name, -2) != '[]')) {
					$name .= '[]';
				}
			} else {
				$multiple = '';
			}
			unset($attribs['multiple']);
		}
		
		$xhtml = '<select' . ' name="' . $info['name'] . '"' . ' id="' . $info['id'] . '"' . $multiple . $this->_htmlAttribs($attribs) . ">";
		
		$list = array();		
		foreach((array) $options as $opt_value => $opt_label) {
			if(is_array($opt_label)) {
				$opt_disable = '';
				$opt_id = ' id="' . $info['id'] . '-optgroup-' . $this->view->escape($opt_value) . '"';
				$list[] = '<optgroup' . $opt_disable . $opt_id . ' label="' . $this->view->escape($opt_value) . '">';
				foreach($opt_label as $val => $lab) {
					$list[] = $this->_build($val, $lab, $value);
				}
				$list[] = '</optgroup>';
			} else {
				$list[] = $this->_build($opt_value, $opt_label, $value);
			}
		}		
		$xhtml .= implode("", $list) . "</select>";		
		return $xhtml;
	}
	
	private function _build($value, $label, $selected) {	
		$opt = '<option' . ' value="' . $this->view->escape($value) . '"' . ' label="' . $this->view->escape($label) . '"';		
		if(in_array((string) $value, $selected)) {
			$opt .= ' selected="selected"';
		}		
		$opt .= '>' . $this->view->escape($label) . "</option>";		
		return $opt;
	}
}